package com.ygg.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ygg.enums.AuthStatusEnum;
import com.ygg.exception.YyghException;
import com.ygg.helper.JwtHelper;
import com.ygg.model.user.Patient;
import com.ygg.model.user.UserInfo;
import com.ygg.result.ResultCodeEnum;
import com.ygg.service.PatientService;
import com.ygg.service.UserInfoService;
import com.ygg.mapper.UserInfoMapper;
import com.ygg.vo.user.LoginVo;
import com.ygg.vo.user.UserAuthVo;
import com.ygg.vo.user.UserInfoQueryVo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {

    @Resource
    PatientService patientService;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        //判断手机号
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        //判断验证码
        String mobleCode = stringRedisTemplate.opsForValue().get(phone);
        if (!code.equals(mobleCode)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }

        //绑定手机号码 判断是否是第一次微信登录
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = this.query().eq("openid", loginVo.getOpenid()).one();
            if (null != userInfo && userInfo.getPhone() == null) {
                userInfo.setPhone(loginVo.getPhone());
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }

        //userInfo=null 说明手机直接登录
        if (null == userInfo) {
            //判断该手机号是否已经存在
            userInfo = this.query().eq("phone", phone).one();
            //不存在则创建
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setStatus(1);
                userInfo.setPhone(phone);
                this.save(userInfo);
            }

        }


        //查看是否被禁用
        if (userInfo.getStatus() == 0) {
            throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
        }

        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);

        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);

        return map;
    }

    @Override
    public void userAuth(UserAuthVo userAuthVo, Long userId) {
        //1.根据用户id查询用户信息
        UserInfo userInfo = this.getById(userId);
        if (userInfo == null) {
            throw new YyghException(ResultCodeEnum.FAIL);
        }
        //2.设置认证信息
        userInfo.setName(userAuthVo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(2);
        //3.进行信息更新
        boolean b = this.updateById(userInfo);
        if (!b) {
            throw new YyghException(ResultCodeEnum.FAIL);
        }
    }

    @Override
    public UserInfo show(Long id) {
        UserInfo userInfo = this.getById(id);
        if (userInfo == null) throw new YyghException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        return userInfo;
    }

    @Override
    public Page<UserInfo> getPage(Integer page, Integer limit, UserInfoQueryVo userInfoQueryVo) {
        String name = userInfoQueryVo.getKeyword();//姓名
        Integer status = userInfoQueryVo.getStatus();//状态
        Integer authStatus = userInfoQueryVo.getAuthStatus();//认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();//开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();//结束时间

        //分页构造器
        Page<UserInfo> infoPage = new Page<>(page, limit);

        Page<UserInfo> newPage = this.query().like(!StringUtils.isEmpty(name), "name", name)
                .eq(!StringUtils.isEmpty(status), "status", status)
                .gt(!StringUtils.isEmpty(createTimeBegin), "create_time", createTimeBegin)
                .lt(!StringUtils.isEmpty(createTimeEnd), "create_time", createTimeEnd)
                .eq(!StringUtils.isEmpty(authStatus), "auth_status", authStatus)
                .page(infoPage);

        //封装认证状态和用户状态
        newPage.getRecords().forEach(this::packageUserInfo);

        return newPage;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (userId != null && status != null) {
            if (status == 0 || status == 1) {
                UserInfo userInfo = new UserInfo();
                userInfo.setId(userId);
                userInfo.setStatus(status);
                this.updateById(userInfo);
            }
        }


    }

    @Override
    public Map<String, Object> userShow(Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = this.show(userId);
        map.put("userInfo", userInfo);
        List<Patient> allUserId = patientService.findAllUserId(userId);
        map.put("patientList", allUserId);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if (userId != null && authStatus != null) {
            if (authStatus == 2 || authStatus == -1) {
                UserInfo userInfo = baseMapper.selectById(userId);
                userInfo.setAuthStatus(authStatus);
                baseMapper.updateById(userInfo);
            }
        }
    }

    private void packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);

    }
}




